<template>
	<n-layout has-sider style='height:100%;'>
		<n-layout-sider v-bind='siderConfig' :collapsed='menusStore["isCollapsed"]'
						:native-scrollbar='false'>
			<n-menu ref='menusRef' v-bind='menuConfig'
					:value='tabsStore["currentActivatedTab"]'
					:collapsed='menusStore["isCollapsed"]'/>
		</n-layout-sider>
	</n-layout>
</template>
<script lang='ts' setup>
import { computed, defineAsyncComponent, h, nextTick, onBeforeMount, reactive, ref, VNodeChild } from 'vue';
import { useCommonStore } from '@/config/pinia/common.store.ts';
import { useTabsStore } from '@/config/pinia/tabs.store.ts';
import { useMenusStore } from '@/config/pinia/menus.store.ts';
import { VxeUI } from '@/config/vxe/index.ts';
import type { CommonMenuProps } from '#/Menu.d.ts';
import type { JsonResultProps } from '#/JsonResult.d.ts';
import axios from '@/config/axios/index.ts';
import { homeCode } from '@/config/pinia/menus.store.config.ts';
import { LayoutSiderProps, MenuGroupOption, MenuOption } from 'naive-ui';
const SvgIcon = defineAsyncComponent(() => import('@/components/customComponents/icon/SvgIcon.vue'));
const ClassIcon = defineAsyncComponent(() => import('@/components/customComponents/icon/ClassIcon.vue'));
// 状态存储
const commonStore = useCommonStore();
const tabsStore = useTabsStore();
const menusStore = useMenusStore();
const menusRef = ref();
let menuList = computed(() => menusStore.menuList);
const siderConfig = reactive<LayoutSiderProps>({
	bordered       : true,
	collapseMode   : 'width',
	collapsedWidth : 65,
	width          : 250,
	position       : 'static'
	/*onCollapse     : store.commit('menu/triggerCollapseStatus'),
	 onExpand       : store.commit('menu/triggerCollapseStatus')*/
});
// @ts-ignore
const menuConfig: MenuProps = reactive({
	accordion         : true,
	mode              : 'vertical',
	iconSize          : 20,
	collapsedIconSize : 24,
	collapsedWidth    : 65,
	keyField          : 'menuCode',
	labelField        : 'menuName',
	childrenField     : 'children',
	disabledField     : 'disabled',
	// @ts-ignore
	options     : menuList,
	renderLabel : (option: MenuOption | MenuGroupOption) => renderLabel(option),
	renderIcon  : (option: MenuOption) => renderIcon(option),
	/*renderExtra   : (option: MenuOption | MenuGroupOption) => renderExtra(option),*/
	onUpdateValue : (key: string, item: MenuOption) => addTab(item as CommonMenuProps)
	/*expandIcon        : (option: MenuOption) => expandIcon(option),*/
});
// 挂载前
onBeforeMount(() => {
	initAll();
});
// 方法
const renderLabel = (option: MenuOption | MenuGroupOption): VNodeChild => {
	// console.log(option);
	if ('href' in option) {
		return h('a', { href : option.href, target : '_blank' }, option['menuName'] as string);
	}
	return h('span', option['menuName'] as string);
};
const renderIcon = (option: MenuOption): VNodeChild => {
	// 如果menuIconType有值,但是menuIcon却并没有填写
	// 为了显示完整的缩进
	// 会渲染一个空图标占位符以保持缩进
	if (option['menuIconType'] && !option['menuIcon']) {
		return true;
	}
	if ('class' === option['menuIconType']) {
		// @ts-ignore
		return h(ClassIcon, { 'icon-class' : option['menuIcon'] });
	} else if ('svg' === option['menuIconType']) {
		let iconType;
		if ((option['menuIcon'] as string).match('fa-')) {
			iconType = 'fa';
		} else if ((option['menuIcon'] as string).match('iconfont5-')) {
			iconType = 'iconfont5';
		} else {
			iconType = 'customized';
		}
		// @ts-ignore
		return h(SvgIcon, { 'icon-type' : iconType, 'icon-class' : option['menuIcon'] });
	}
};
const renderExtra = (option: MenuOption | MenuGroupOption) => {};
/*const expandIcon = (option: MenuOption) => {
 return h(resolveComponent('n-icon'), null, { default : () => h(resolveComponent('n-caret-down-outline')) });
 };*/
const initAll = () => {
	if (sessionStorage.getItem('x-auth-token')) {
		// 如果有x-auth-token代表着已登录,直接请求菜单
		initMenu();
	}
};
const initMenu = () => {
	axios<any, JsonResultProps<any>, any>({
		method : 'GET',
		url    : '/menu'
	}).then((jsonResult: JsonResultProps<any>) => {
		if (jsonResult['status']) {
			const flag = jsonResult.data && Array.isArray(jsonResult.data) && jsonResult.data.length;
			if (flag) {
				menusStore.menuList = jsonResult.data;
				nextTick(() => {
					// 左侧菜单树加载完毕,右侧的Tabs才加载
					commonStore.componentReady().then(() => {
						// 初始化首页展示
						initHomePage(jsonResult.data.find((menu: CommonMenuProps) => homeCode === menu.menuCode));
					});
				});
			}
		} else {
			VxeUI.modal.message({ content : jsonResult['msg'], status : 'warning', id : 'failedMessage' });
		}
	}).catch((error: unknown) => {
		console.error(error);
		VxeUI.modal.message({ content : '系统异常,请稍后再试', status : 'error', id : 'errorMessage' });
	});
};
const initHomePage = (homeMenu: CommonMenuProps) => {
	// 寻找浏览器会话内存中的当前选中页和当前打开页
	const tabs: string | null = sessionStorage.getItem('tabs');
	const currentActivatedTab: string | null = sessionStorage.getItem('currentActivatedTab');
	// 检查tabs和currentActivatedTab是否在会话内存中
	if (tabs && currentActivatedTab) {
		// 在会话内存中就直接从会话中获取
		tabsStore.syncSessionTabsToStore();
	} else {
		// 不在会话内存中就代表了第一次进入该页面,不是刷新页面
		addTab(homeMenu);
	}
};
const addTab = (menu: CommonMenuProps) => {
	nextTick(() => {
		tabsStore.addTab({
			id           : menu.id,
			key          : menu.menuCode,
			menuCode     : menu.menuCode,
			menuName     : menu.menuName,
			menuType     : menu.menuType,
			menuPath     : menu.menuPath,
			menuIcon     : menu.menuIcon,
			menuIconType : menu.menuIconType,
			tabIcon      : menu.tabIcon,
			tabIconType  : menu.tabIconType,
			params       : null,
			isCache      : menu.isCache
			// forceFlush   : false
		});
	});
};
defineExpose({ menusRef });
</script>